package com.itheima.demo2;

import java.util.Scanner;

public class BinarySearchDemo {
    public static void main(String[] args) {
        int[] arr= {1,3,5,6,7,8,9,14,25,36,72,87,98,100};
        System.out.println("请输入你要查找的元素:");
        int number = new Scanner(System.in).nextInt();
        int index = binarySearchDemo(arr,number);
        if (index != -1){
        System.out.println("您查找的数据索引为:"+index);
        }else {
            System.out.println("您查找的数据不在数组中!");
        }
    }

    private static int binarySearchDemo(int[] arr, int number) {
        if (number < arr[0] || number > arr[arr.length-1]){
            return -1;
        }
        int min = 0;
        int max = arr.length-1;
        while (min <= max){
            int mid = (min + max) >> 1;
            if (number == arr[mid]){
                return mid;
            }else if (number < arr[mid]){
                max = mid - 1;
            }else if (number > arr[mid]) {
                min = mid +1;
            }
        }
        return -1;
    }
}
